package com.lingshu.app.config;

import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Environment;
import android.util.DisplayMetrics;

import com.lingshu.app.database.AppDatabase;
import com.lingshu.app.network.NetworkApi;
import com.lingshu.app.network.NetworkRequiredInfo;
import com.lingshu.core.utils.KLog;
import com.lingshu.app.utils.MVUtils;
import com.lingshu.app.utils.MVUtilsEntryPoint;
import com.lingshu.app.messaging.ReceiveMessageService;
import com.lingshu.core.custom.BaseApplication;
import com.lingshu.core.custom.BaseExceptionHandler;
import com.lingshu.core.custom.LocalFileHandler;
import com.lingshu.core.utils.SharedUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import dagger.hilt.android.EntryPointAccessors;
import dagger.hilt.android.HiltAndroidApp;

/**
 * @author 于定金
 * @version 1.0
 * @Date 2023/12/28 13:48
 * @Description
 */
@HiltAndroidApp
public class App extends BaseApplication {
    private static final String TAG = App.class.getName();
    private static AppDatabase db;
    private static MVUtils mvUtils;

    //屏幕的高宽
    public int screenWidth = 0;
    public int ScreenHeight = 0;

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();

        //前台服务
        Intent serviceIntent = new Intent(context, ReceiveMessageService.class);
        startForegroundService(serviceIntent);

        //日志配置
        KLog.init(true);

        //初始化网络框架
        NetworkApi.init(new NetworkRequiredInfo(this));

        //创建本地数据库
        db = AppDatabase.getInstance(this);

        //读取配置地址
        getProperties();

        //创建APP崩溃日志目录
        File appFolder = new File(getDiskCacheDir(this) + "/log");
        if (!appFolder.exists()) appFolder.mkdirs();

        //得到屏幕的高宽
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        screenWidth = displayMetrics.widthPixels;
        ScreenHeight = displayMetrics.heightPixels;
        KLog.d(TAG, "屏幕宽：" + screenWidth);
        KLog.d(TAG, "屏幕高：" + ScreenHeight);

        //sp初始化
        SharedUtils.init(context);

        //mv初始化
        MVUtilsEntryPoint entryPoint = EntryPointAccessors.fromApplication(context, MVUtilsEntryPoint.class);
        mvUtils = entryPoint.getMVUtils();
    }

    @Override
    public BaseExceptionHandler getDefaultUncaughtExceptionHandler() {
        return new LocalFileHandler(context);
    }

    public static Context getContext() {
        return context;
    }

    public static AppDatabase getDb() {
        return db;
    }

    public static MVUtils getMvUtils() {
        return mvUtils;
    }

    /**
     * 获取文件路径
     *
     * @param context
     * @return
     */
    private String getDiskCacheDir(Context context) {
        String cachePath = null;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageEmulated()) {
            cachePath = context.getExternalCacheDir().getAbsolutePath();
        } else {
            cachePath = context.getCacheDir().getAbsolutePath();
        }

        return cachePath;
    }

    /**
     * 获取配置文件信息
     */
    private void getProperties() {
        Properties properties = new Properties();
        AssetManager assetManager = context.getAssets();
        InputStream inputStream = null;
        DefaultConfig defaultConfig = DefaultConfig.getInstance();
        try {
            inputStream = assetManager.open("config.properties");
            properties.load(inputStream);
            String environment = properties.getProperty(Constants.ENVIRONMENT);

            if (environment.equals("development")) {
                defaultConfig.setAuthHost(properties.getProperty(Constants.DEVELOPMENT_AUTH_HOST));
                defaultConfig.setApiHost(properties.getProperty(Constants.DEVELOPMENT_API_HOST));
                defaultConfig.setWebsocketHost(properties.getProperty(Constants.DEVELOPMENT_WEBSOCKET_HOST));
                defaultConfig.setMqHost(properties.getProperty(Constants.DEVELOPMENT_RABBITMQ_HOST));
                defaultConfig.setMqPort(Integer.parseInt(properties.getProperty(Constants.DEVELOPMENT_RABBITMQ_PORT)));
                defaultConfig.setMqUsername(properties.getProperty(Constants.DEVELOPMENT_RABBITMQ_USERNAME));
                defaultConfig.setMqPassword(properties.getProperty(Constants.DEVELOPMENT_RABBITMQ_PASSWORD));
                defaultConfig.setMqVirtualHost(properties.getProperty(Constants.DEVELOPMENT_RABBITMQ_VIRTUALHOST));
            } else {
                defaultConfig.setAuthHost(properties.getProperty(Constants.PRODUCTION_AUTH_HOST));
                defaultConfig.setApiHost(properties.getProperty(Constants.PRODUCTION_API_HOST));
                defaultConfig.setWebsocketHost(properties.getProperty(Constants.PRODUCTION_WEBSOCKET_HOST));
                defaultConfig.setMqHost(properties.getProperty(Constants.PRODUCTION_RABBITMQ_HOST));
                defaultConfig.setMqPort(Integer.parseInt(properties.getProperty(Constants.PRODUCTION_RABBITMQ_PORT)));
                defaultConfig.setMqUsername(properties.getProperty(Constants.PRODUCTION_RABBITMQ_USERNAME));
                defaultConfig.setMqPassword(properties.getProperty(Constants.PRODUCTION_RABBITMQ_PASSWORD));
                defaultConfig.setMqVirtualHost(properties.getProperty(Constants.PRODUCTION_RABBITMQ_VIRTUALHOST));
            }
        } catch (IOException e) {
            KLog.e(TAG, e.getMessage());
        }
    }
}
